var querystring = require("querystring"),
  fs = require("fs"),
  formidable = require("formidable");
/**
 * 返回一个一页面
 * @param {*} response 
 */
function start(response, request, io) {
  console.log("Request handler 'start' was called.");
  fs.createReadStream('index.html').pipe(response);
}
function starts(response) {
  console.log("Request handler 'start' was called.");

  var body = "";
  body = `<html>
              <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
              </head>
            <body>
              <form action="/upload" enctype="multipart/form-data" method="post">
                <input type="file" name="upload" multiple="multiple">
                <input type="submit" value="Upload file" />
                </form>
            </body>
            </html>`
  response.writeHead(200, { "Content-Type": "text/html" });
  response.write(body);
  response.end();
}
/**
 * 处理请求的图片并保存
 * @param {*} response 
 * @param {*} request 
 */
function upload(response, request, io) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();

  form.uploadDir = "./upload";//必须设置

  console.log("about to parse");
  form.on('progress', function (bytesReceived, bytesExpected) {

    //response.write(bytesReceived.toString());
  
    io.emit('total',{total:bytesExpected})
    io.emit('numbers', { size: bytesReceived,total:bytesExpected});

  });
  form.on('fileBegin', function (name, file) {
    console.log(file.size);
  });
  form.on('end', function () {
    console.log('end');
  })

  form.parse(request, function (error, fields, files) {

    var type = files.upload.type.substr(files.upload.type.indexOf('/') + 1);
    var size = files.upload.size;
    console.log(type);
    fs.renameSync(files.upload.path, "./upload/" + size + "." + type);

    response.writeHead(200, { "Content-Type": "text/html" });
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
  });
}


/**
 * 返回二进制文件的路径
 * @param {*} response 
 */
function show(response, requeset, io) {

  fs.readFile(__dirname + "/upload/test.png", "binary", function (error, file) {
    if (error) {
      response.writeHead(500, { "Content-Type": "text/plain" });
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, { "Content-Type": "image/png" });
      response.write(file, "binary");
      response.end();
    }
  });
}

function aa(response) {
  response.write('hello world');
  response.end();
}

exports.start = start;
exports.upload = upload;
exports.show = show;

exports.aa = aa;